//
//  GeneralTool.m
//  jingjing2.0
//
//  Created by apple on 16/4/27.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "GeneralTool.h"
#import "NSString+MD5.h"
#import "AFNetworkReachabilityManager.h"
@implementation GeneralTool

//获得时间戳
+(NSString*)gettimestamp
{
    //时间戳
        NSDate* date = [NSDate dateWithTimeIntervalSinceNow:0];
        NSTimeInterval time=[date timeIntervalSince1970];
        NSString *timeString = [NSString stringWithFormat:@"%.0f",time];
        return timeString;
}


//获得加密标志
+(NSString*)GetSin:(NSDictionary*)dict
{
    NSArray *keys = [dict allKeys];
    NSArray *sortedArray = [keys sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2){
        return [obj1 compare:obj2 options:NSNumericSearch];
    }];
    
    NSMutableString*str_sin=[[NSMutableString alloc] init];
    
    for (NSString*str in sortedArray) {
        
        if(!IsNilString([dict objectForKey:str]))
        {
            [str_sin appendString:[NSString stringWithFormat:@"%@=%@&",str,[dict objectForKey:str]]];
        }
    }
    [str_sin appendString:@"Key=B75E5CDF1D9A0FDD"];
    NSString*str1= [[GeneralTool md5UpStr:str_sin] uppercaseString];

    return  str1;
    
    
}

//md5加密
+(NSString *)md5UpStr:(NSString *)str
{
    const char *cStr = [str UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(cStr, (int)strlen(cStr), result);
    
    return [[NSString stringWithFormat: @"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
             result[0], result[1], result[2], result[3],
             result[4], result[5], result[6], result[7],
             result[8], result[9], result[10], result[11],
             result[12], result[13], result[14], result[15]
             ] lowercaseString];

}

//判断手机号码格式
+ (NSString *)valiMobile:(NSString *)mobile{
    if (mobile.length < 11)
    {
        return @"手机号长度只能是11位";
    }else{
        /**
         * 移动号段正则表达式
         */
        NSString *CM_NUM = @"^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\\d{8}|(1705)\\d{7}$";
        /**
         * 联通号段正则表达式
         */
        NSString *CU_NUM = @"^((13[0-2])|(145)|(15[5-6])|(176)|(18[5,6]))\\d{8}|(1709)\\d{7}$";
        /**
         * 电信号段正则表达式
         */
        NSString *CT_NUM = @"^((133)|(153)|(177)|(18[0,1,9]))\\d{8}$";
        NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM_NUM];
        BOOL isMatch1 = [pred1 evaluateWithObject:mobile];
        NSPredicate *pred2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU_NUM];
        BOOL isMatch2 = [pred2 evaluateWithObject:mobile];
        NSPredicate *pred3 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT_NUM];
        BOOL isMatch3 = [pred3 evaluateWithObject:mobile];
        
        if (isMatch1 || isMatch2 || isMatch3) {
            return nil;
        }else{
            return @"请输入正确的手机号码";
        }
    }
    return nil;
}
//验证邮箱
+ (BOOL) validateEmail:(NSString *)email
{
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:email];
}
//判断是否有网络连接
+(NSString *)isConnectNet
{
    static NSString *str=nil;
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];

    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        
        switch (status) {
                
            case AFNetworkReachabilityStatusNotReachable:{
                
                str=@"无网络";
                
                break;
                
            }
                
            case AFNetworkReachabilityStatusReachableViaWiFi:{
                
                str=@"WiFi网络";
            break;
                
            }
                
            case AFNetworkReachabilityStatusReachableViaWWAN:{
                str=@"无线网络";
              break;
                
            }
                
            default:
                
                break;
                
        }
        
    }];
    return str;
}
//隐藏
+(void)hideTabBar
{
    UIWindow * wind = [UIApplication sharedApplication].keyWindow;
    TabBarController* zd = (TabBarController *)wind.rootViewController;
    [zd hideTabBar];
}

//显示
+(void)showTabBar{
    UIWindow * wind = [UIApplication sharedApplication].keyWindow;
    TabBarController* zd = (TabBarController *)wind.rootViewController;
    [zd showTabBar];
}
#pragma mark--获取我的默认地址

+(void)getMyAddressListWithIsDefault:(NSString *)isDefault andReuqestBlock:(void(^)(id response,NSError * error))block
{
    //http://192.168.1.107:3722/User/UserAddr/{UserCode}/{GetType}/{CityCode}/{Timestamp}/{Sign}
    ///{UserCode}/{GetType}/{CityCode}/{Timestamp}/{Sign}
    //type @"DEFAULT"获取一条默认
    //type @"MORE"获取所有地址列表
    //获取地址列表时 从下单进去和从地址管理进去两个界面不一样，从订单进去要判断地址是否在当前城市（用isCanUSe区分），如果不是则不能点击，可以点击的话，点击的时候还要调一个该笔订单的地址是否在服务范围的接口
    NSString *timeStamp=[GeneralTool gettimestamp];
    NSDictionary *dic=@{@"UserCode":GETUSERCODE,
                        @"GetType":isDefault,
                        @"CityCode":GETCITYCODE,
                        @"Timestamp":timeStamp};
    NSString *sign=[GeneralTool GetSin:dic];
    NSString *urlString=[NSString stringWithFormat:@"User/UserAddr/%@/%@/%@/%@/%@",GETUSERCODE,isDefault,GETCITYCODE,timeStamp,sign];
    [RequestTool requestDataWithType:@"get" andUrlString:urlString andParameters:nil andRequestFinished:^(id responses, NSError *error) {
        if (responses)
        {
            block(responses,nil);
        }
        if (error)
        {
            block(nil,error);
        }
    }];
}
#pragma mark--获取我的可用优惠券

+(void)getMyCouponWithIsCanUse:(NSString *)isCanUSe andPageIndex:(NSInteger)count andReuqestBlock:(void(^)(id response,NSError * error))block
{
    //http://192.168.1.107:3722/User/MyCoupon/{UserCode}/{IsCanUse}/{PageIndex}/{PageSize}/{Timestamp}/{Sign}
    //isCanUse @"1"可用 @"0"不可用
    //PageIndex页面数 0-4
    //PageSize一页放几张优惠券 5
    //每次刷新PageIndex＋＝5;
    NSString *timeStamp=[GeneralTool gettimestamp];
    NSDictionary *dic=@{@"UserCode":GETUSERCODE,
                        @"IsCanUse":isCanUSe,
                        @"PageIndex":[NSString stringWithFormat:@"%zd",count],
                        @"PageSize":@"10",
                        @"Timestamp":timeStamp};
    NSString *sign=[GeneralTool GetSin:dic];
    NSString *urlSTring=[NSString stringWithFormat:@"User/MyCoupon/%@/%@/%@/%@/%@/%@",GETUSERCODE,@"1",[NSString stringWithFormat:@"%zd",count],@"10",timeStamp,sign];
    [RequestTool requestDataWithType:@"get" andUrlString:urlSTring andParameters:nil andRequestFinished:^(id responses, NSError *error) {
        if (error) {
            block(nil,error);
        }else
        {
            block(responses,nil);
        }
    }];
    
}

@end
